<?php

namespace app\api\controller;

use app\api\exception\TokenException;
use app\common\library\ApiResponse;
use think\Controller;
use think\facade\Request;
use app\common\model\User;
use think\Db;

class Base extends Controller
{
    use ApiResponse;

    /**
     * 当前用户的登录状态
     *
     * @var boolean
     */
    protected $loginState = 'nologin';

    /**
     * 当前登录的用户id
     *
     * @var integer
     */
    protected $uid = 2;

    /**
     * 当前页码
     *
     * @var integer
     */
    protected $page = 1;

    /**
     * 当前加载数据条数
     *
     * @var integer
     */
    protected $size = 10;
    
    public function initialize()
    {
        //开启检测token
        //$this->checkToken();

        //获取用户的登录状态
        $this->loginState = $this->checkLogin();

        $page = input('param.page/d', 1);
        $size = input('param.size/d', 10);
        $this->page = $page < 1 ? 1 : $page;
        $this->size = $size < 1 || $size > 100 ? 10 : $size;
    }

    /**
     * token验证
     *
     * @return void
     */
    protected function checkToken()
    {
        $token = Request::header('token', '');
        if (empty($token)) {
            abort(402);
        }
    }


    /**
     * 用户登录后的身份认证
     *
     * @return void
     */
    protected function checkLogin()
    {
        $auth = Request::header('auths', '');
        if (empty($auth)) {
            //未登录的情况
            return 'nologin';
        }

        $user = new User();
        $res = $user->checkLoginToken($auth);
        if (false === $res) {
            return $user->getError();
        } elseif ('timeout' == $res) {
            //登录超时
            return 'timeout';
        } elseif (is_numeric($res) && $res != '0') {
            $this->uid = $res;
        } else if (true !== $res) {
            return 'timeout';
        }

        $uid = Db::name('user')->where('id', $this->uid)->value('id');
        if (empty($uid)) {
            return 'nologin';
        }

        return true;
    }

    /**
     * 获取当前用户登录状态，如果非true，则返回客户端数据
     *
     * @return void
     */
    protected function getLoginState()
    {

        //验证登录
        if (true === $this->loginState) {
            return true;
        } elseif ($this->loginState == 'nologin') {
            return self::nologin();
        } elseif ($this->loginState == 'timeout') {
            return self::errors('登录超时');
        } elseif (true !== $this->loginState) {
            return self::errors('身份认证失败');
        }

        return true;
    }
}
